package com.fauks.se.design_mode.代理模式.dynamic_proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * cglib工厂，产生代理类
 */
public class MyCglibFactory implements MethodInterceptor {

    //返回CalcImpl增强类
    CalcImpl myCglibCreator() {
        //增强器对象
        Enhancer enhancer = new Enhancer();
        //设置代理对象的父类即目标类
        enhancer.setSuperclass(CalcImpl.class);
        //回调接口对象
        enhancer.setCallback(this);
        //返回CalcImpl的增强类（代理对象）
        Object o = enhancer.create();
        return (CalcImpl) o;
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("方法执行了...");
        Object invoke = method.invoke(new CalcImpl(), args);
        System.out.println("方法结束了...");
        return invoke;
    }
}
